﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace PartitionsCodegen
{
    public partial class MainForm : Form
    {

        int board_limit_x;
        int board_limit_y;
        int dwell_time_z;
        int dwell_time_copies;

        public MainForm()
        {
            
           InitializeComponent();
           comboBoxCopies.SelectedIndex = Properties.Settings.Default.copies-1;
           if (Properties.Settings.Default.to_the_right)
               radioButtonRight.Select();
           else radioButtonUp.Select();

           //string depths = Properties.Settings.Default.depths.Replace(",", "\r\n");
           textBoxDepths.Text = Properties.Settings.Default.depths;

           textBoxOffsetX.Text = Properties.Settings.Default.offset_x;
           textBoxOffsetY.Text = Properties.Settings.Default.offset_y;
           textBoxCode.Text = Properties.Settings.Default.code;
           dwell_time_z = Properties.Settings.Default.dwell_time_z;
           dwell_time_copies = Properties.Settings.Default.dwell_time_copies;
           checkBoxLift.Checked = Properties.Settings.Default.lift_between_zs;
           textBoxZLift.Text = Properties.Settings.Default.z_for_lifts;
           board_limit_x = Properties.Settings.Default.board_limit_x;
           board_limit_y = Properties.Settings.Default.board_limit_y;

           FormClosing += MainForm_FormClosing;



               

           
        }


  

        public int getCopies() { return Int32.Parse(comboBoxCopies.SelectedItem.ToString()); }

        public bool getToTheRight() { return radioButtonRight.Checked; }

        public float[] getDepths() {

            string depths_data =textBoxDepths.Text.Replace('.',',');
            depths_data = depths_data.Replace("\r", "");
            string[] depths_s = depths_data.Split('\n');

            float[] depths = new float[depths_s.Length];

            int depths_count = 0;

            for (int i = 0; i < depths.Length; i++)
            {
                if (depths_s[i].Length <= 0) continue;
                depths_count++;                
                depths[i] = float.Parse(depths_s[i]);
            }

            float[] final_depths = new float[depths_count];
            int count=0;
            for (int i = 0; i < depths.Length; i++)
            {
                if (depths_s[i].Length <= 0) continue;
                final_depths[count]=depths[i];
                count++;
            }


            return final_depths; 
        }



        public decimal getOffsetX() { return decimal.Parse(textBoxOffsetX.Text.Replace('.', ',')); }
        public decimal getOffsetY() { return decimal.Parse(textBoxOffsetY.Text.Replace('.', ',')); }
        public string getCode() { 
            
            return textBoxCode.Text.ToUpper().Replace('.',',');     ;
        }

        public bool getLiftBetweenZs(){ return checkBoxLift.Checked;}
        public float getZForLifts() { return float.Parse(textBoxZLift.Text.Replace('.',',')); }

        public int getBoardLimitX(){return board_limit_x;}
        public int getBoardLimitY(){return board_limit_y;}
        public int getDwellTimeZ(){return dwell_time_z;}
        public int getDwellTimeCopies() { return dwell_time_copies; }

        public void setBoardLimitX(int data) { board_limit_x = data; }
        public void setBoardLimitY(int data) { board_limit_y = data; }
        public void setDwellTimeZ(int data) { dwell_time_z = data; }
        public void setDwellTimeCopies(int data) { dwell_time_copies = data; }




        private void label1_Click_1(object sender, EventArgs e) { 
        }



        public void errorAlert(string alert_msg)
        {
        
        
        DialogResult dlgRes = MessageBox.Show(alert_msg,   "Error",    
        MessageBoxButtons.OK, 
        MessageBoxIcon.Error);        
       }



        private string validateCopies()
        {
            int ret;
            bool ok = Int32.TryParse(comboBoxCopies.SelectedItem.ToString(), out ret);
            if (!ok) return "N° de copias inválido.  Seleccione un valor numérico mayor que cero\n";
            if (ret <= 0) return "N° de copias debe ser un número mayor que cero\n";
            return "";
        }

        private string validateOrientation()
        {
            if(!(radioButtonRight.Checked||radioButtonUp.Checked)) return "Debe seleccionar orientación a la derecha o izquierda\n";
            return "";
        }

        private string validateOffsetX()
        {
            float ret;
            bool ok = Single.TryParse(textBoxOffsetX.Text, out ret);
            if (!ok) return "Ingrese número válido en Offset X\n";
            return "";        
        }

        private string validateOffsetY()
        {
            float ret;
            bool ok = Single.TryParse(textBoxOffsetY.Text, out ret);
            if (!ok) return "Ingrese número válido en Offset Y\n";
            return "";
        }

        private string validateDepths()
        {

            if (textBoxDepths.Text.Length <= 0) return "Debe ingresar al menos una profundidad de corte\n";

            string depths_data =textBoxDepths.Text;
            depths_data = depths_data.Replace("\r", "");
            string[] depths_s = depths_data.Split('\n');

            string errors = "";

            for (int i = 0; i < depths_s.Length; i++)
            {
                if (depths_s[i].Length <= 0) continue;
                float parsed;
                bool ok = Single.TryParse(depths_s[i], out parsed);

                if (!ok) errors += "Valor de profundidad \"" + depths_s[i] + "\" no es un número válido\n";

            }

            return errors;
            
        
        }

        private string validateCodeNotEmpty()
        {
            if (textBoxCode.Text.Length <= 0) return "Código vacío\n";
            return "";
        }

        private string validateZForLifts()
        {
            float ret;
            bool ok = Single.TryParse(textBoxZLift.Text, out ret);
            if (!ok) return "Ingrese número válido en Z para alzas\n";
            return "";
        }

        private void generate(bool clipboard)
        {

            string errors = validateCopies() + validateOrientation() + validateOffsetX() + validateOffsetY() + validateZForLifts()+validateDepths() + validateCodeNotEmpty();


            if (errors.Length > 0) errorAlert(errors);
            else
            {
                Program.generate(clipboard);

                if(clipboard)
                { 
                DialogResult dlgRes = MessageBox.Show("Código generado y copiado al portapapeles", "Partition Codegen",
                MessageBoxButtons.OK,
                MessageBoxIcon.Information);
                }

            }


        
        }

        private void button1_Click(object sender, EventArgs e)
        {
            generate(true);
        }

        private void button2_Click(object sender, EventArgs e)
        {
            generate(false);

        }

        private void pictureBox2_Click(object sender, EventArgs e)
        {
            //Open settings form
            SettingsForm sf = new SettingsForm(this,board_limit_x,board_limit_y,dwell_time_z,dwell_time_copies);
            sf.ShowDialog();
        }


        private void MainForm_FormClosing(Object sender, FormClosingEventArgs e)
        {
            Properties.Settings.Default.copies = comboBoxCopies.SelectedIndex + 1;
            Properties.Settings.Default.to_the_right = radioButtonRight.Checked;
            
            //string depths = Properties.Settings.Default.depths.Replace(",", "\r\n");
            Properties.Settings.Default.depths = textBoxDepths.Text;

            Properties.Settings.Default.offset_x = textBoxOffsetX.Text;
             Properties.Settings.Default.offset_y=textBoxOffsetY.Text ;
             Properties.Settings.Default.code=textBoxCode.Text ;
             Properties.Settings.Default.dwell_time_z=dwell_time_z;
             Properties.Settings.Default.dwell_time_copies = dwell_time_copies;
             Properties.Settings.Default.lift_between_zs = checkBoxLift.Checked;
             Properties.Settings.Default.z_for_lifts = textBoxZLift.Text;
             Properties.Settings.Default.board_limit_x = board_limit_x;
             Properties.Settings.Default.board_limit_y = board_limit_y;

            Properties.Settings.Default.Save();

            
       
        }

        private void guardarToolStripMenuItem_Click(object sender, EventArgs e)
        {

            DialogResult result = saveFileDialog1.ShowDialog();
            if (result == DialogResult.OK)
            {
                writeFile(saveFileDialog1.FileName);

            }

        }

        private void cargarToolStripMenuItem_Click(object sender, EventArgs e)
        {
            DialogResult result = openFileDialog1.ShowDialog();
            if (result == DialogResult.OK)
            {
                
               string [] fields = readFile(openFileDialog1.FileName);


               comboBoxCopies.SelectedIndex = Int32.Parse(fields[0])-1;
               if (fields[1].Contains("rue"))
                   radioButtonRight.Select();
               else radioButtonUp.Select();

               textBoxDepths.Text = fields[2];

               textBoxOffsetX.Text = fields[3];
               textBoxOffsetY.Text = fields[4];
               textBoxCode.Text = fields[11];
               dwell_time_z = Int32.Parse(fields[9]);
               dwell_time_copies = Int32.Parse(fields[10]); 
               checkBoxLift.Checked = fields[6].Contains("rue");
               textBoxZLift.Text = fields[5];
               board_limit_x = Int32.Parse(fields[7]); 
               board_limit_y = Int32.Parse(fields[8]);

               string fname = Path.GetFileName(openFileDialog1.FileName);
               MessageBox.Show("Archivo \"" + fname + "\" cargado correctamente", "PartitionsCodegen",
               MessageBoxButtons.OK,
               MessageBoxIcon.Information);
            }




        }

        public string[] readFile(string path)
        {

            string text = File.ReadAllText(path);
            string [] sep = {"%-&-%"};
            return text.Split(sep, StringSplitOptions.None);
        
        }

        public void writeFile(string path)
        { 
            string sep = "%-&-%";
            string[] fields = new string[12];
            fields[0] = "" + (1 + comboBoxCopies.SelectedIndex);
            fields[1] = ""+radioButtonRight.Checked;
            fields[2]= textBoxDepths.Text;
            fields[3] = textBoxOffsetX.Text;
            fields[4] = textBoxOffsetY.Text;
            fields[5] = textBoxZLift.Text;
            fields[6] = ""+checkBoxLift.Checked;
            fields[7] = ""+board_limit_x;
            fields[8] = "" + board_limit_y;
            fields[9] = "" + dwell_time_z;
            fields[10] = "" + dwell_time_copies;
            fields[11] = textBoxCode.Text;

            
            string text = "";
            for (int i = 0; i < fields.Length; i++)
            {
                text += fields[i];
                if(i<fields.Length-1)text+=sep;
            
            }

                File.WriteAllText(path, text);
                string fname = Path.GetFileName(path);
                MessageBox.Show("Archivo \"" + fname + "\" guardado correctamente", "PartitionsCodegen",
                MessageBoxButtons.OK,
                MessageBoxIcon.Information);

        
        }



    }
}
